package com.hsgene.gateway.support.filter;

import com.hsgene.authority.dto.ClientRequestDto;
import com.hsgene.common.ClientType;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.gateway.service.api.LoginCheckService;
import com.hsgene.gateway.support.ClientRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 小程序请求过滤器
 *
 * @author wangbing
 * @version 1.0, 2018/11/9
 */
@Component
public class AppletsClientRequestFilter implements ClientRequestFilter {

    private final static Logger LOGGER = LoggerFactory.getLogger(AppletsClientRequestFilter.class);

    @Resource
    private LoginCheckService loginCheckService;

    @Override
    public ClientType filterType() {
        return ClientType.APPLETS;
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter(HttpServletRequest request) {
        // 此处为运营后台用户权限校验
        return true;
    }

    @Override
    public ApiResult run(HttpServletRequest request) {
        ClientRequestDto clientRequestDto = new ClientRequestDto(request);
        String sessionId = clientRequestDto.getHeaders().get("session_id");
        String accessToken = clientRequestDto.getHeaders().get("access_token");
        ApiResult<UserInfo> loginCheckResult = loginCheckService.checkLoginStatus(sessionId, accessToken);
        if (!loginCheckResult.isSucc()) {
            LOGGER.error("用户登录检测失败：" + loginCheckResult.getData());
            return loginCheckResult;
        }
        return ApiResult.succ();
    }
}
